package com.linkdood.app.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linkdood.app.domain.CustomRole;
import com.linkdood.app.domain.SysRoleMenu;
import com.linkdood.app.mapper.CustomRoleMapper;
import com.linkdood.app.service.CustomRoleService;
import com.linkdood.app.service.SysRoleMenuService;
import com.linkdood.app.utils.PaginationUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 自定义角色
 *
 * @author hycao
 */
@Slf4j
@Service
public class CustomRoleServiceImpl extends ServiceImpl<CustomRoleMapper, CustomRole> implements CustomRoleService {
    private final SysRoleMenuService sysRoleMenuService;

    public CustomRoleServiceImpl(SysRoleMenuService sysRoleMenuService) {
        this.sysRoleMenuService = sysRoleMenuService;
    }


    /**
     * 添加角色及权限到角色权限表
     *
     * @param customRole
     */
    @Override
    public void saveRoleMenu(CustomRole customRole) {
        JSONArray objects = JSON.parseArray(customRole.getMenus());
        List<SysRoleMenu> modelList = new ArrayList<>(objects.size());
        for (Object object : objects) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(customRole.getId());
            sysRoleMenu.setMenuId(String.valueOf(object));
            modelList.add(sysRoleMenu);
        }
        sysRoleMenuService.saveBatch(modelList);
    }

    @Override
    public Page<CustomRole> pageCustomRoleByRoleNames(String roleName,  Pageable pageable) {
        return lambdaQuery().like(StringUtils.isNotBlank(roleName), CustomRole::getName, roleName).page(PaginationUtil.getPage(pageable));
    }

    @Override
    public Optional<CustomRole> getCustomRoleByName(String name) {
        return lambdaQuery().eq(CustomRole::getName, name).oneOpt();
    }

}
